﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;

namespace uzing
{
    public class uzCTcpServer
    {
        TcpListener listener;
        uzCTcpClientSync client;
        bool isStarted;

        public uzCTcpServer()
        {
            client = null;
            listener = null;
            isStarted = false;
        }

        public void OpenServer(int Port)
        {
            listener = new TcpListener(IPAddress.Any, Port);
            listener.Start();
        }

        private uzCTcpClientSync getClient(TcpClient Client)
        {
            uzCTcpClientSync _client = new uzCTcpClientSync();
            _client.RegisterClient(Client);
            return _client;
        }

        public uzCTcpClientSync CheckForNewConnection(UZING_TCP Mode)
        {
            if (null == listener)
            {
                return null;
            }

            if (UZING_TCP.BLOCKING == Mode)
            {
                TcpClient _client = listener.AcceptTcpClient();
                return getClient(_client);
            }
            else if (UZING_TCP.NON_BLOCKING == Mode)
            {
                if (!isStarted)
                {
                    listener.BeginAcceptTcpClient(acceptCallback, listener);
                    isStarted = true;
                }

                if (client != null)
                {
                    uzCTcpClientSync _client = client;
                    client = null;
                    return _client;
                }
                else
                {
                    return null;
                }
            }
            else
            {
                listener.BeginAcceptTcpClient(acceptCallback, listener);
                return null;
            }
        }

        private void acceptCallback(IAsyncResult ar)
        {
            TcpClient _client = listener.EndAcceptTcpClient(ar);
            client = getClient(_client);
            isStarted = false;
        }
    }
}


